package com.cakebackoffice;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.cakebackoffice.Model.Order;


public class OrderActivity extends Activity {
    /**
     * Called when the activity is first created.
     */

    private ListView lv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // On met le XML
        setContentView(R.layout.orderlist);
        lv = (ListView) findViewById(R.id.ListView);

        // Affiche la listview
        refreshListView();

        // Ajout du listener pour les touch simple à la list catalog_detail_product
        lv.setOnItemClickListener(simpleTouchListenner);

        // Ajout du menu pour les touch long
        registerForContextMenu(lv);


    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshListView();
    }

    private ListView.OnItemClickListener simpleTouchListenner = new ListView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            // Petit toast
            Toast toast = Toast.makeText(getBaseContext(), "Displaying the order of " + ((Order) (adapterView.getItemAtPosition(i))).getClient().getName(), Toast.LENGTH_SHORT);
            toast.show();

            viewOrder((Order) adapterView.getItemAtPosition(i));
        }
    };


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {


        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();


        switch (item.getItemId()) {
            case R.id.button_view:
                Toast.makeText(this, "Displaying the order.",
                        Toast.LENGTH_SHORT).show();
                viewOrder((Order) lv.getItemAtPosition((int) info.id));
                return true;
            case R.id.button_setDone:
                SyncTaskManager.deleteOrderFromServer((Order) lv.getItemAtPosition((int) info.id));
                return true;
            case R.id.button_delete:
                setAlertBeforeDelete((Order) lv.getItemAtPosition((int) info.id));
                return true;
            default:

                return super.onContextItemSelected(item);
        }


    }

    public void LaunchCreateOrder(View view) {
        Intent intent = new Intent(this, FormActivity.class);
        startActivity(intent);
    }

    public void LaunchAdminPanel(View view) {
        Intent intent = new Intent(this, AdminPanelActivity.class);
        startActivity(intent);
    }

    private void viewOrder(Order order) {
        Intent intent = new Intent(this, OrderSheetActivity.class);
        intent.putExtra("orderIdDB", Integer.parseInt(order.getIdDB().toString()));
        startActivity(intent);
    }

    public void Reload(View view) {
        new reloadAsyncTask(this).execute();
    }

    private class reloadAsyncTask extends SyncTaskManager.orderUpdate {

        public reloadAsyncTask(Context context) {
            super(context);
        }

        @Override
        protected void onPreExecute() {
            Toast.makeText(context, "Recupération des commandes", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute(Integer i) {
                    super.onPostExecute(i);
            Integer j = i - 100;
            Toast.makeText(context, j.toString() + " commandes", Toast.LENGTH_SHORT).show();
            if (j > 0) {
                refreshListView();
            }
        }
    }

    private void setAlertBeforeDelete(final Order orderToDelete) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to delete this order? It can't be undone.")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        try {
                            orderToDelete.removeFromDatabase(OrderActivity.this);
                            SyncTaskManager.deleteOrderFromServer(orderToDelete);
                            Toast.makeText(OrderActivity.this, "Deleted", Toast.LENGTH_SHORT).show();
                            refreshListView();
                        } catch (Exception e) {
                            Toast.makeText(OrderActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                        }

                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private void refreshListView() {
        try {
            ListAdapter adapter = new ListViewOrderAdapter(this, R.layout.listitemorder, Order.getAll(this));
            lv.setAdapter(adapter);
        } catch (Exception e) {
            Toast.makeText(this, "Unable to refresh", Toast.LENGTH_SHORT);
        }

        lv.setTextFilterEnabled(true);
        lv.setItemsCanFocus(false);

    }


}
